TARGET=test
CC=arm-none-eabi-gcc
OBJCOPY=arm-none-eabi-objcopy

RM=rm -f
CORE=3
CPUFLAGS=-mthumb -mcpu=cortex-m$(CORE)

INCFLAGS=-I $(shell pwd)/Libraries/CMSIS -I $(shell pwd)/Libraries/STM32F10x_StdPeriph_Driver/inc -I $(shell pwd)/user
LDFLAGS = -T stm32_flash.ld -Wl,-cref,-u,Reset_Handler -Wl,-Map=$(TARGET).map -Wl,--gc-sections -Wl,--defsym=malloc_getpagesize_P=0x80 -Wl,--start-group -lc -lm -Wl,--end-group

CFLAGS=$(INCFLAGS) -D STM32F10X_HD -D USE_STDPERIPH_DRIVER -Wall -g

START_SRC=$(shell find ./ -name 'startup_stm32f10x_hd.s')
START_OBJ=$(START_SRC:%.s=%.o)
C_SRC=$(shell find ./ -name '*.c')
C_OBJ=$(C_SRC:%.c=%.o)

INTERRFACE_CFG=/usr/local/share/openocd/scripts/interface/stlink-v2.cfg      # 这里就是下载器的配置文件，可以在前面提到的文件夹中找到对应下载器的配置文件
TARGET_CFG=/usr/local/share/openocd/scripts/target/stm32f1x.cfg 

$(TARGET):$(START_OBJ) $(C_SRC)
	$(CC) $^ $(CPUFLAGS) $(LDFLAGS) $(CFLAGS) -o $(TARGET).elf
	$(OBJCOPY) $(TARGET).elf $(TARGET).bin
	$(OBJCOPY) $(TARGET).elf -Oihex $(TARGET).hex

$(START_OBJ):$(START_SRC)
	$(CC) -c $^ $(CPUFLAGS) $(CFLAGS) -o $@

$(C_OBJ):%.o:%.c
	$(CC) -c $^ $(CPUFLAGS) $(CFLAGS) -o $@

clean:
	$(RM) $(shell find ./ -name '*.o') $(TARGET).*

# 这个是一键下载，如果不是stlink下载器可以改对应的变量
download:
	openocd -f $(INTERRFACE_CFG) -f $(TARGET_CFG) -c init -c halt -c "flash write_image erase $(PWD)/$(TARGET).bin" -c reset -c shutdown

